package top.hmtools.configuration;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.io.FileUtils;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.alibaba.druid.pool.DruidDataSourceFactory;


/**
 * 配置mybatis与数据源，本套对象实例用于本项目的业务流程相关操作
 * @author HyboJ
 *
 */
@Configuration
public class DataSourceMybatisConfiguration {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

private static final String SQLSESSION_BEAN_NAME="sqlSessionFactoryBean"; 

	/**
	 * 获取druid数据库连接池
	 * @param gmConfiguration
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("static-access")
	@Bean
	@DependsOn(value="GMConfiguration")
	public DataSource druidDataSource(GMConfiguration gmConfiguration) throws Exception{
		//初始化数据库文件
		gmConfiguration.loadProperties(null);
		Properties properties = gmConfiguration.getProperties();
		String url = properties.getProperty("url");
		if(url.contains("sqlite")){
			String sqliteDataPath = url.trim().replaceFirst("jdbc:sqlite:", "");
			InputStream sqliteBaseDB = this.getClass().getClassLoader().getResourceAsStream("hm-gm.db");
			File sqliteDB = new File(sqliteDataPath);
			sqliteDataPath = sqliteDB.getAbsolutePath();
			if(!sqliteDB.exists()){
				try {
					FileUtils.copyInputStreamToFile(sqliteBaseDB, sqliteDB);
					logger.info("成功复制初始SQLite数据库文件到"+sqliteDataPath);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}else{
				logger.info(sqliteDataPath+"已存在，不需要复制初始SQLite数据库文件。");
			}
		}
		
	    DruidDataSourceFactory druidDataSourceFactory = new DruidDataSourceFactory();
	    DataSource ds = druidDataSourceFactory.createDataSource(properties);
	    return ds;
	}
    
	/**
	 * 自动扫描指定包路径
	 * @param sqlSessionFactory
	 * @param applicationContext
	 * @return
	 */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(SqlSessionFactory sqlSessionFactory,ApplicationContext applicationContext){
        MapperScannerConfigurer configurer = new MapperScannerConfigurer();
        configurer.setApplicationContext(applicationContext);
        configurer.setBasePackage("top.hmtools.daos.**");
        configurer.setSqlSessionFactoryBeanName(SQLSESSION_BEAN_NAME);
        return configurer;
    }

    /**
     * 获取mybatis session  工厂
    * 方法说明：                    sqlSessionFactoryBean
    * 输入参数说明：           @param dataSource
    * 输入参数说明：           @return
    * 输入参数说明：           @throws Exception
    * 输出参数说明：           SqlSessionFactory
    *
    *
     */
    @Bean(SQLSESSION_BEAN_NAME)
    public SqlSessionFactory sqlSessionFactoryBean(DataSource dataSource)
            throws Exception {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);

        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:mappers/*.xml"));
        return sqlSessionFactoryBean.getObject();
    }
    
    /**
     * 获取SqlSessionTemplate
     * 
     * @return
     */
  @Bean
  public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
      return new SqlSessionTemplate(sqlSessionFactory);
  }
}
